import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from "@/common/layer";
import axios from 'axios';
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Mymooncake extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isPrize: 0,
            name: '',
            tellphone: '',
            address: '',
            second: 0,
            code: ''
        }
        this.valids = [
            {
                key: 'name',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("姓名不能为空")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'tellphone',
                func(str) {
                    if (str.length !== 11) {
                        jquery(".errormsg").html("手机号码格式错误")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'code',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("验证码不能为空")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'address',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("家庭地址不能为空")
                        return false
                    }
                    return true
                }
            }
        ]

    }
    componentDidMount() {
        this.isprize()
        jquery(".prizes ul").on("click", "li", function () {
            var src = jquery(this).children('.cake').attr("src");
            jquery('.imgbox .bigimg').attr('src', src)
        });
    }


    async isprize() {
        var openid = sessionStorage.getItem("openid")
        let res = await util.rjax({
            url: '/prizeUser/queryList?openId=' + openid,
            type: 'get',
        })

        if (res) {//请求和响应code都为200
            this.setState({ cakeList: res.data.rows });
            for (let i in res.data.rows) {
                var num = res.data.rows[i].type
                jquery(".cakebox li:nth-child(" + num + ") .cake").attr("src", res.data.rows[i].link);
                jquery(".cakebox li:nth-child(" + num + ") span").html(res.data.rows[i].count);
                this.setState({ isPrize: res.data.rows[i].isPrize })
            }
            if (this.state.isPrize == 1) {
                jquery('.apply').show()
            }
        }
    }

    async closedialog() {
        jquery('.apply').hide()
    }

    nameChange(e) {
        this.setState({
            name: e.target.value
        })
    }

    phoneChange(e) {
        this.setState({
            tellphone: e.target.value
        })
    }

    codeChange(e) {
        this.setState({
            code: e.target.value
        })
    }

    addressChange(e) {
        this.setState({
            address: e.target.value
        })
    }

    async submitSuccess() {
        jquery('.submitdialog').hide()
    }

    async beforeSendCode() {
        if (this.state.second !== 0) { return }
        if (this.state.tellphone.length < 11) {
            jquery(".errormsg").html("手机格式错误")
            return
        } else {
            jquery(".errormsg").empty()
        }

        this.setState({
            second: 60
        });

        let time = setInterval(() => {
            if (this.state.second < 1) {
                clearInterval(time)
            } else {
                this.setState({
                    second: this.state.second - 1
                })
            }
        }, 1000)

        let phone = this.state.tellphone
        let res = await axios.get(`${util.host}/auth/code/sms`, {
            params: {
                deviceId: phone,
                phone: phone
            }
        })

        if (res.data.success) {
            jquery(".errormsg").html("验证码发送成功")
        } else {
            jquery(".errormsg").html("手机号码格式错误")
        }
    }

    async beforeSubmit() {
        for (let item of this.valids) {
            if (!item.func(this.state[item.key])) {
                return;
            }
        }

        var openId = sessionStorage.getItem("openid")
        let sendobj = {
            address: this.state.address,
            name: this.state.name,
            openId: openId,
            phone: this.state.tellphone,
            smsCode: this.state.code
        }

        let res = await util.rjax({ url: '/prizeUser/insertPrizeUser', type: "POST", data: sendobj }).catch((res) => {
            if (res.data.msg === "请勿重复申请") {
                layer.open({
                    content: res.data.msg,
                    btn: '好的'
                })
                this.setState({
                    second: 0,
                })
                jquery('.applydialog').hide()
            } else {
                layer.open({
                    content: res.data.msg,
                    btn: '好的'
                })
                this.setState({
                    second: 0,
                })
            }
        })

        if (res) {
            jquery('.applydialog').hide()
            jquery('.submitdialog').show()
        }
    }


    render() {
        return (
            <div>
                <div id="mooncake">
                    <div className="prizes">
                        <div className="imgbox">
                            <img className="bigimg" src="/assets/wechat/cake_hao.png" alt="" />
                            <img className="cloudimg" src="/assets/wechat/cloud.png" alt="" />
                        </div>

                        <ul className="cakebox">
                            <li>
                                <img className="cake" src="" alt="" />
                                <img className="plate" src="/assets/wechat/plate.png" alt="" />
                                <span></span>
                            </li>
                            <li>
                                <img className="cake" src="" alt="" />
                                <img className="plate" src="/assets/wechat/plate.png" alt="" />
                                <span></span>
                            </li>
                            <li>
                                <img className="cake" src="" alt="" />
                                <img className="plate" src="/assets/wechat/plate.png" alt="" />
                                <span></span>
                            </li>
                            <li>
                                <img className="cake" src="" alt="" />
                                <img className="plate" src="/assets/wechat/plate.png" alt="" />
                                <span></span>
                            </li>
                            <li>
                                <img className="cake" src="" alt="" />
                                <img className="plate" src="/assets/wechat/plate.png" alt="" />
                                <span></span>
                            </li>
                        </ul>

                        <div className="smallcloud">
                            <img className="cloudimg" src="/assets/wechat/cloud.png" alt="" />
                        </div>
                    </div>

                    {/* cake-prize-dialog */}
                    <div className="apply">
                        <div className="applydialog">
                            <p className="prizemsg">恭喜你!</p>
                            <p className="msg">已集齐“好礼送不停”五种月饼，<br></br>请填写个人信息等待客服联系。</p>
                            <img className="closeimg" src="http://img0.rongsue.com/FqRJoUj9TKA1FKqZUSdG51Kumhed" onClick={this.closedialog.bind(this)} alt="" />
                            <div style={{ position: "relative" }}>
                                <span className="phonehead">姓名</span>
                                <input type="text" className="text" autoComplete="off" placeholder="姓名" value={this.state.name} onChange={this.nameChange.bind(this)} maxLength="11" />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="phonehead">+86</span>
                                <input type="text" className="text" autoComplete="off" placeholder="请输入手机号" value={this.state.tellphone} onChange={this.phoneChange.bind(this)} maxLength="11" />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="codehead">验证码</span>
                                <input type="text" className="text" autoComplete="off" placeholder="请输入验证码" value={this.state.code} onChange={this.codeChange.bind(this)} />
                                <input type="button" className="yzbtn" value={(this.state.second === 0) ? '验证码' : `剩余${this.state.second}秒`} onClick={this.beforeSendCode.bind(this)} />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="cityhead">家庭地址</span>
                                <input type="text" className="text" autoComplete="off" placeholder="江苏省南京市" value={this.state.address} onChange={this.addressChange.bind(this)} />
                            </div>

                            <span className="errormsg"></span>
                            <input type="button" className="btn" value="确定" onClick={this.beforeSubmit.bind(this)} />
                        </div>
                    </div>

                    {/* submitdialog */}
                    <div className="submitdialog">
                        <span className="mt30">提交成功!</span>
                        <span className="mt10">客服会尽快与您取得联系！</span>
                        <button onClick={this.submitSuccess.bind(this)}>确定</button>
                    </div>

                </div>
            </div >
        )
    }
}
ReactDom.render(< Mymooncake />, document.getElementById("app"));